package com.swak.frame.filter.adapter;

import java.util.ServiceLoader;

import com.google.common.collect.Lists;
import com.swak.frame.chain.Filter;
import com.swak.frame.chain.FilterChain;
import com.swak.frame.chain.FilterChainFactory;

/**
 * SPI责任链模式工厂
 * 
 * @author colley.ma
 * @date 2018/04/17
 */
public class SpiFilterChainFactoryAdapter<T> implements FilterChainFactoryAdapter<T> {

    private Class<? extends Filter<T>> clazz;

    private FilterChain<T> filterChain;

    public SpiFilterChainFactoryAdapter() {};

    public SpiFilterChainFactoryAdapter(Class<? extends Filter<T>> clazz) {
        this.clazz = clazz;
    }

    private FilterChain<T> buildFilterChain(Class<? extends Filter<T>> clazz) {
        ServiceLoader<? extends Filter<T>> filters = ServiceLoader.load(clazz);
        return FilterChainFactory.buildFilterChain(Lists.newArrayList(filters.iterator()));
    }

    @Override
    public FilterChain<T> getFilterChain() {
        if (this.filterChain == null) {
            this.filterChain = buildFilterChain(clazz);
        }
        return this.filterChain;

    }
}
